import React, { Component } from 'react';
import { connect } from 'dva';
import { getDateInterval } from "../../../utils/utils";
import {
  Input,
  Button,
  Form,
  Select,
  Radio,
  DatePicker,
  Upload,
  Icon,
  message,
  InputNumber
} from 'antd';
import './less/contract.less';
import * as api from "../../../services/api";
import PSelect from "../../../components/Pro/PSelect";

const FormItem = Form.Item;
const { Option } = Select.Option;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const config = {
  rules: [
    {
      type: 'object',
      required: false,
      message: '请选择日期!'
    }
  ]
}
@connect(state => ({ profile: state.profile }))
@Form.create()

export default class Devices extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      contractType: "01",
      distributionModeList: [],//发放/结算方式
      contractListName: [],//合同类型下拉
      currentRow: {
        contractType: '',//合同类型
        contractName: '',//合同名称
        comFileNo: '',//企业档案编号
        comParty: '',//企业所在方
        firstPartyName: '',//甲方名称
        firstPartyTel: '',//甲方联系电话
        secondPartyName: '',//乙方名称
        secondPartyTel: '',//乙方联系电话
        effectStartDate: null,//生效开始日期
        effectEndDate: null,//生效终止日期
        payAmount: '',//付费金额
        payDate: null,//付费日期
        secondPartyIdCardNo: '',//乙方身份证号码
        workPost: '',//工作岗位
        content: '',//工作/劳务内容
        postSalary: '',//岗位薪资
        periodSalary: '',//试用期工资
        distributionMode: '',//发放/结算方式
        workPlace: '',//工作/劳务地点'
        serviceAmount: '',//劳务费用
        serviceTotalAmount: '',//劳务总金额
        agreementSignDate: null,//协议签订日期
        contractUrl: '',//合同文件url
        remark: '',//备注
        comContractId: '',//合同ID
        period: '',//试用期
      },
      fileList: [],
      fileNumber: 0,
      timeLimit: '',
    };
    //文件上传
    const that = this;
    that.modelUpload = {
      name: 'xfile',
      action: api.uploadUrl,
      beforeUpload() {
        const number = that.state.fileNumber === 0;
        if (!number) {
          message.success('上传成功，但只能上传一份合同文件');
        }
        return number;
      },
      onChange(info) {
        const { setFieldsValue } = that.props.form;
        let { fileList } = info;
        fileList = fileList.slice(-1);
        console.log(fileList, 'filist');
        that.setState({ fileList });
        if (info.file.status === 'removed') {
          that.setState({
            fileNumber: 0
          });
        }
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList, 'uploading');
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} 文件上传成功`);
          console.log('fileList', fileList[0].response.data);
          that.setState({ contractUrl: fileList[0].response.data });
          setFieldsValue({ contractUrl: fileList[0].response.data });
          that.setState({
            fileNumber: 1
          });
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 文件上传失败.`);
        }
      },
    };
  }
  //生命周期
  componentDidMount = () => {
    this.DistributionModeList();
    this.GetCompanyNameAndPhone();
  };


  GetCompanyNameAndPhone = () => {
    api.enterpriseComContractInitComContract({}).then((data) => {
      if (data.data) {
        console.log('公司公司', data.data);
        this.setState({
          currentRow: {
            firstPartyName: data.data.firstPartyName,
            firstPartyTel: data.data.firstPartyTel,
            comParty: '1',
            contractType: '',//合同类型
            contractName: '',//合同名称
            comFileNo: '',//企业档案编号
            secondPartyName: '',//乙方名称
            secondPartyTel: '',//乙方联系电话
            effectStartDate: null,//生效开始日期
            effectEndDate: null,//生效终止日期
            payAmount: '',//付费金额
            payDate: null,//付费日期
            secondPartyIdCardNo: '',//乙方身份证号码
            workPost: '',//工作岗位
            content: '',//工作/劳务内容
            postSalary: '',//岗位薪资
            periodSalary: '',//试用期工资
            distributionMode: '',//发放/结算方式
            workPlace: '',//工作/劳务地点'
            serviceAmount: '',//劳务费用
            serviceTotalAmount: '',//劳务总金额
            agreementSignDate: null,//协议签订日期
            contractUrl: '',//合同文件url
            remark: '',//备注
            comContractId: '',//合同ID
            period: '',//试用期
          }
        });
      }
    });
  };

  DistributionModeList = () => {
    api.getDictInformation({ codeTypes: 'distributionMode' }).then((data) => {
      console.log('发放/结算方式data:', data);
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          distributionModeList: data.data.distributionMode,
        });
      }
    });
  };

  //合同有效期-合同期限
  validDeadlineChange = (date, dateString) => {
    console.log("合同期限变化", date, dateString);
    this.setState({ timeLimit: getDateInterval(date) });
  }
  //点击移除文件
  onRemoveUrl = () => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({ contractUrl: '' });
    this.setState({
      fileNumber: 0
    });
  };

  //报表类型 change
  pSelectChange = (value, type) => {
    console.log(value, type);
    this.setState({ contractType: value });
  };

  //发放/结算方式
  renderDistributionModeList = () => {
    return this.state.distributionModeList.map((val, key) => {
      return <Option key={key} value={val.codeValue + ""}>{val.label}</Option>;
    });
  };

  //校验金额
  checkJinE = (rule, value, callback) => {
    if (value === ' ') {
      callback('输入不能为空！');
    } else if (value && !(/^([1-9][0-9]*|0)(\.[0-9]{1,2})?$/).test(value)) {
      callback('输入不正确！');
    } else {
      callback();
    }
  };

  //校验试用期
  checkNumber = (rule, value, callback) => {
    if (value && !(/^[1-9]\d*$/).test(value)) {
      callback('操作数量格式不正确！');
    } else {
      callback();
    }
  };

  selectView = () => {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 10
        },
        md: {
          span: 8
        }
      }
    };
    const { getFieldDecorator } = this.props.form;
    const currentContractType = this.state.contractType;
    if (currentContractType === "01") {
      return (
        <div>
          <FormItem {...formItemLayout} label="联系电话">
            {getFieldDecorator('secondPartyTel', { initialValue: this.state.currentRow.secondPartyTel })(<Input placeholder="请输入" maxLength="20" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同有效期">
            {getFieldDecorator('effectDate')(<RangePicker onChange={this.validDeadlineChange} format={dateFormat} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同期限">
            {getFieldDecorator('contractPeriod', {
              initialValue: this.state.timeLimit
            })(< Input disabled />)}
          </FormItem>
          <FormItem {...formItemLayout} label="付费金额">
            {getFieldDecorator('payAmount', {
              initialValue: this.state.currentRow.payAmount,
              rules: [{
                validator: this.checkJinE
              }]
            })(<Input placeholder="请输入" maxLength="8" suffix="元" style={{ width: 400 }} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="付费日期">
            {getFieldDecorator('payDate', config)(<DatePicker />)}
          </FormItem>
        </div>
      );
    }
    if (currentContractType === "02") {
      return (
        <div>
          <FormItem {...formItemLayout} label="身份证号码">
            {getFieldDecorator('secondPartyIdCardNo', { initialValue: this.state.currentRow.secondPartyIdCardNo })(<Input placeholder="请输入" maxLength="18" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="联系电话">
            {getFieldDecorator('secondPartyTel', { initialValue: this.state.currentRow.secondPartyTel })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同有效期">
            {getFieldDecorator('effectDate', {})(<RangePicker onChange={this.validDeadlineChange} format={dateFormat} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同期限">
            {getFieldDecorator('contractPeriod', {
              initialValue: this.state.timeLimit
            })(< Input disabled />)}
          </FormItem>
          <FormItem {...formItemLayout} label="试用期">
            {getFieldDecorator('period', {
              initialValue: this.state.currentRow.period,
              rules: [
                {
                  required: false
                }, {
                  validator: this.checkNumber
                }
              ]
            })(<div><InputNumber min={0} max={999} style={{ width: '370px' }} maxLength="3" /><span>月</span></div>)}
          </FormItem>
          <FormItem {...formItemLayout} label="工作岗位">
            {getFieldDecorator('workPost', { initialValue: this.state.currentRow.workPost })(<Input placeholder="请输入岗位名称" maxLength="20" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="岗位工资">
            {getFieldDecorator('postSalary', {
              initialValue: this.state.currentRow.postSalary,
              rules: [{
                validator: this.checkJinE
              }]
            })(<Input suffix="元" style={{ width: 400 }} placeholder="请输入" maxLength="8" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="试用期工资">
            {getFieldDecorator('periodSalary', {
              initialValue: this.state.currentRow.periodSalary,
              rules: [{
                validator: this.checkJinE
              }]
            })(<Input suffix="元" style={{ width: 400 }} placeholder="请输入" maxLength="8" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="按">
            {getFieldDecorator('distributionMode', {
              initialValue: this.state.currentRow.distributionMode
            })(
              <PSelect style={{ width: '365px', marginRight: '8px' }} type="distributionMode" />
            )}
            <span>发放</span>
          </FormItem>
        </div>
      );
    }
    if (currentContractType === "03") {
      return (
        <div>
          <FormItem {...formItemLayout} label="身份证号码">
            {getFieldDecorator('secondPartyIdCardNo', { initialValue: this.state.currentRow.secondPartyIdCardNo })(<Input placeholder="请输入" maxLength="18" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="联系电话">
            {getFieldDecorator('secondPartyTel', { initialValue: this.state.currentRow.secondPartyTel })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同有效期">
            {getFieldDecorator('effectDate', {})(<RangePicker onChange={this.validDeadlineChange} format={dateFormat} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同期限">
            {getFieldDecorator('contractPeriod', {
              initialValue: this.state.timeLimit
            })(< Input disabled />)}
          </FormItem>
          <FormItem {...formItemLayout} label="试用期">
            {getFieldDecorator('period', {
              initialValue: this.state.currentRow.period,
              rules: [
                {
                  required: false
                }, {
                  validator: this.checkNumber
                }
              ]
            })(<div><InputNumber min={0} max={999} style={{ width: '370px' }} maxLength="3" /><span>月</span></div>)}
          </FormItem>
          <FormItem {...formItemLayout} label="工作内容">
            {getFieldDecorator('content', {
              initialValue: this.state.currentRow.content
            })(<Input placeholder="请输入岗位及内容" maxLength="20" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="岗位工资">
            {getFieldDecorator('postSalary', {
              initialValue: this.state.currentRow.postSalary,
              rules: [{
                validator: this.checkJinE
              }]
            })(<Input suffix="元" style={{ width: 400 }} placeholder="请输入" maxLength="8" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="试用期工资">
            {getFieldDecorator('periodSalary', {
              initialValue: this.state.currentRow.periodSalary,
              rules: [{
                validator: this.checkJinE
              }]
            })(<Input suffix="元" style={{ width: 400 }} placeholder="请输入" maxLength="8" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="按">
            {getFieldDecorator('distributionMode', {
              initialValue: this.state.currentRow.distributionMode
            })(
              <PSelect style={{ width: '365px', marginRight: '8px' }} type="distributionMode" />
            )}
            <span>发放</span>
          </FormItem>
        </div>
      );
    }
    if (currentContractType === "04") {
      return (
        <div>
          <FormItem {...formItemLayout} label="身份证号码">
            {getFieldDecorator('secondPartyIdCardNo', { initialValue: this.state.currentRow.secondPartyIdCardNo })(<Input placeholder="请输入" maxLength="18" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="联系电话">
            {getFieldDecorator('secondPartyTel', { initialValue: this.state.currentRow.secondPartyTel })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同有效期">
            {getFieldDecorator('effectDate', {})(<RangePicker onChange={this.validDeadlineChange} format={dateFormat} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="合同期限">
            {getFieldDecorator('contractPeriod', {
              initialValue: this.state.timeLimit
            })(< Input disabled />)}
          </FormItem>
          <FormItem {...formItemLayout} label="劳务内容">
            {getFieldDecorator('content', { initialValue: this.state.currentRow.content })(<Input placeholder="请输入劳务内容" maxLength="20" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="劳务地点">
            {getFieldDecorator('workPlace', { initialValue: this.state.currentRow.workPlace })(<Input placeholder="请输入劳务地点" maxLength="30" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="劳务费用">
            {getFieldDecorator('serviceAmount', {
              initialValue: this.state.currentRow.periodSalary,
              rules: [{
                validator: this.checkJinE
              }]
            })(<Input suffix="元" style={{ width: 400 }} placeholder="请输入" maxLength="8" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="按">
            {getFieldDecorator('distributionMode', {
              initialValue: this.state.currentRow.distributionMode,
            })(
              <PSelect style={{ width: '365px', marginRight: '8px' }} type="distributionMode" />)}
            <span>发放</span>
          </FormItem>
          <FormItem {...formItemLayout} label="劳务总金额">
            {getFieldDecorator('serviceTotalAmount', {
              initialValue: this.state.currentRow.periodSalary,
              rules: [{
                validator: this.checkJinE
              }]
            })(<Input suffix="元" style={{ width: 400 }} placeholder="请输入" maxLength="8" />)}
          </FormItem>
        </div>
      );
    }
  };
  handleAddContractSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('values', values);
        console.log('urlurl', this.state.fileNumber);
        console.log('合同文件的值', values.contractUrl);
        if (values.agreementSignDate && values.agreementSignDate !== undefined) {
          values.agreementSignDate = values['agreementSignDate'].format('YYYY-MM-DD');
        } else {
          values.agreementSignDate = '';
        }
        if (values.effectDate && values.effectDate !== undefined) {
          values.effectStartDate = values['effectDate'][0].format('YYYY-MM-DD');
          values.effectEndDate = values['effectDate'][1].format('YYYY-MM-DD');
          delete values.effectDate;
        } else {
          values.effectStartDate = '';
          values.effectEndDate = '';
          delete values.effectDate;
        }
        if (values.payDate && values.payDate !== undefined) {
          values.payDate = values['payDate'].format('YYYY-MM-DD');
        } else {
          values.payDate = '';
        }
        api.enterpriseComContractInsertComContract({ ...values }).then(() => {
          message.success('保存成功！');
          setTimeout(() => { this.props.history.push(`/contractManagement/contractList`); }, 1000);
        }, (err1) => {
          console.log(err1);
        });
      }
    });
  };

  //验证企业档案编号
  checkComFileNo = (rule, value, callback) => {
    if (value && !(/^[0-9a-zA-Z]+$/).test(value)) {
      callback('请输入正确的企业档案编号！');
    } else {
      callback();
    }
  };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if (value && !(/^0\d{2,3}-?\d{7,8}$/).test(value)) {
      callback('请输入正确的联系方式！');
    } else {
      callback();
    }
  };


  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 10
        },
        md: {
          span: 10
        }
      }
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="addContract">
        <div>
          <Form className="addContract-form" onSubmit={this.handleAddContractSubmit}>
            <FormItem {...formItemLayout} label="合同类型">
              {getFieldDecorator('contractType', {
                initialValue: this.state.currentRow.contractType,
                rules: [
                  {
                    required: true,
                    message: '请选择合同类型'
                  }
                ]
              })(
                <PSelect style={{ width: 400 }} placeholder="请选择" type="contractType" onChange={this.pSelectChange} />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="合同名称">
              {getFieldDecorator('contractName', {
                initialValue: this.state.currentRow.contractName,
                rules: [
                  {
                    required: true,
                    message: '请输入合同名称'
                  }
                ]
              })(<Input placeholder="请输入" maxLength="30" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="企业档案编号">
              {getFieldDecorator('comFileNo', {
                initialValue: this.state.currentRow.comFileNo,
                rules: [
                  {
                    required: true,
                    message: "请输入企业档案编号"
                  }, {
                    validator: this.checkComFileNo
                  }
                ]
              })(<Input placeholder="请输入" maxLength="30" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="我方为">
              {getFieldDecorator('comParty', {
                initialValue: this.state.currentRow.comParty,
                rules: [
                  {
                    required: true,
                    message: "请选择甲方/乙方"
                  }
                ]
              })(
                <RadioGroup style={{ width: 400 }} onChange={this.onChangeRadio}>
                  <Radio value={'1'}>甲方</Radio>
                  <Radio value={'2'}>乙方</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="甲方">
              {getFieldDecorator('firstPartyName', { initialValue: this.state.currentRow.firstPartyName })(<Input placeholder="请输入" maxLength="30" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="联系电话">
              {getFieldDecorator('firstPartyTel', { initialValue: this.state.currentRow.firstPartyTel })(<Input placeholder="请输入" maxLength="20" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="乙方">
              {getFieldDecorator('secondPartyName', { initialValue: this.state.currentRow.secondPartyName })(<Input placeholder="请输入" />)}
            </FormItem>
            {this.selectView()}
            <FormItem {...formItemLayout} label="协议签订日期">
              {getFieldDecorator('agreementSignDate', config)(<DatePicker />)}
            </FormItem>
            <FormItem {...formItemLayout} label="合同备注信息">
              {getFieldDecorator('remark', { initialValue: this.state.currentRow.remark })(<TextArea rows={4} placeholder="请输入合同备份" maxLength="300" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="合同文件备注">
              {getFieldDecorator('contractUrl', {
                initialValue: this.state.currentRow.contractUrl,
                rules: [
                  {
                    required: true,
                    message: "请上传文件"
                  }
                ]
              })(<div style={{ width: 400 }}>
                <Upload
                  defaultFileList={[]}
                  fileList={this.state.fileList}
                  {...this.modelUpload}
                  onRemove={this.onRemoveUrl}
                >
                  <Button style={{ marginRight: "8px" }}><Icon type="upload" />上传文件</Button>
                  支持扩展名：.doc\.docx\.pdf\.jpg\.png
                </Upload>
              </div>)}
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" onClick={
                () => { this.props.history.push(`/contractManagement/contractList`); }
              }>取消
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleAddContractSubmit}>保存</Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}
